//-----------------------------------------------------------------------
// <copyright file="CreateBranch.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <author>Giles Knap [Updated 03 Apr 08: Mike Fourie - Code Cleanup, TFS 2008 Support, Workingdirectory Support etc.]</author>
// <date>2006-03-23</date>
// <summary>Creates a SourceTfs branch</summary>
//-----------------------------------------------------------------------

namespace Microsoft.Sdc.Tasks.SourceTfs
{
    using System;
    using System.Globalization;
    using Microsoft.Build.Framework;
    using Microsoft.Sdc.Tasks.Configuration;

    /// <summary>
    /// Creates the branch specified
    /// </summary>
    /// <remarks>
    /// <code><![CDATA[
    /// <SourceTfs.CreateBranch SourcePath="sourcePath" DestinationPath="destinationPath" TfsVersion="tfsVersion" WorkingDirectory="workingDirectory" OverrideText="overrideText"/>]]></code>
    /// <para>where:</para>
    /// <para><i>SourcePath (Required)</i></para>
    /// <para>The root of the path from which to create the branch.</para>
    /// <para><i>DestinationPath (Required)</i></para>
    /// <para>The root of that path of the new branch</para>
    /// <para><i>tfsVersion</i></para>
    /// <para>Version of TFS to use. Supports 2005 and 2008. Default is 2005</para>
    /// <para><i>workingDirectory</i></para>
    /// <para>Specifies the WorkingDirectory to run TF.exe in. This determines the workspace</para>
    /// <para><i>overrideText</i></para>
    /// <para>Text to use when overriding checkin policies. Using override may cause a warning.</para>   
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <Target Name="Test" >
    ///         <SourceTfs.CreateBranch
    ///             SourcePath="$/Depot/Main/Working/" 
    ///             DestinationPath="$/Depot/Main/Release/..."
    ///         />
    ///     </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>
    public class CreateBranch : TaskBase
    {
        private string destinationPath;
        private string sourcePath;
        private string tfsVersion = "2005";
        private string workingDirectory;
        private string overrideText;

        /// <summary>
        /// Gets or sets the override.
        /// </summary>
        /// <value>The override.</value>
        public string Override
        {
            get { return this.overrideText; }
            set { this.overrideText = value; }
        }

        /// <summary>
        /// Gets or sets the working directory.
        /// </summary>
        /// <value>The working directory.</value>
        public string WorkingDirectory
        {
            get { return this.workingDirectory; }
            set { this.workingDirectory = value; }
        }

        /// <summary>
        /// Gets or sets the TFS version.
        /// </summary>
        /// <value>The TFS version.</value>
        public string TfsVersion
        {
            get { return this.tfsVersion; }
            set { this.tfsVersion = value; }
        }

        /// <summary>
        /// Gets or sets the mapping from the source files of the branch (left) to the target files of the branch (right) in the depot. The destinationPath maps from one location in the depot to another.
        /// </summary>
        /// <value>The mapping from the source files of the branch (left) to the target files of the branch (right) in the depot. The destinationPath maps from one location in the depot to another.</value>
        [Required]
        public string DestinationPath
        {
            get { return this.destinationPath; }
            set { this.destinationPath = value; }
        }

        /// <summary>
        /// Gets or sets the name of the new branch
        /// </summary>
        /// <value>The name of the new branch</value>
        [Required]
        public string SourcePath
        {
            get { return this.sourcePath; }
            set { this.sourcePath = value; }
        }

        /// <summary>
        /// Performs the action of this task.
        /// </summary>
        protected override void InternalExecute()
        {
            Log.LogMessageFromResources("SourceTfs.CreateBranchStart");
            Helper h = new Helper(this.TfsVersion);
            string arguments = String.Format(CultureInfo.InvariantCulture, "branch \"{0}\" \"{1}\" /noprompt", this.sourcePath, this.destinationPath);
            ShellExecute shellExecute = new ShellExecute(h.TfExePath, arguments);
            if (string.IsNullOrEmpty(this.WorkingDirectory) == false)
            {
                shellExecute.WorkingDirectory = this.WorkingDirectory;
            }

            Log.LogMessage(MessageImportance.Normal, string.Format("Executing {0} with {1}", shellExecute.Filename, arguments));
            int returnValue = shellExecute.Execute();
            Log.LogMessage(MessageImportance.Low, shellExecute.StandardOutput);

            switch (returnValue)
            {
                case 1:
                    Log.LogWarning("Exit Code 1. Partial success: " + shellExecute.StandardError.Trim());
                    break;
                case 2:
                    Log.LogError("Exit Code 2. Unrecognized command: " + shellExecute.StandardError.Trim());
                    break;
                case 100:
                    Log.LogError("Exit Code 100. Nothing Succeeded: " + shellExecute.StandardError.Trim());
                    break;
            }

            arguments = String.Format(CultureInfo.InvariantCulture, "checkin \"{0}\" /noprompt /recursive", this.destinationPath);
            if (string.IsNullOrEmpty(this.Override) == false)
            {
                arguments += " /override:\"" + this.Override + "\"";
            }

            shellExecute = new ShellExecute(h.TfExePath, arguments);
            if (string.IsNullOrEmpty(this.WorkingDirectory) == false)
            {
                shellExecute.WorkingDirectory = this.WorkingDirectory;
            }
            
            Log.LogMessage(MessageImportance.Normal, string.Format("Executing {0} with {1}", shellExecute.Filename, arguments));
            returnValue = shellExecute.Execute();
            Log.LogMessage(MessageImportance.Low, shellExecute.StandardOutput);

            switch (returnValue)
            {
                case 1:
                    Log.LogWarning("Exit Code 1. Partial success: " + shellExecute.StandardError.Trim());
                    break;
                case 2:
                    Log.LogError("Exit Code 2. Unrecognized command: " + shellExecute.StandardError.Trim());
                    break;
                case 100:
                    Log.LogError("Exit Code 100. Nothing Succeeded: " + shellExecute.StandardError.Trim());
                    break;
            }

            Log.LogMessageFromResources("SourceTfs.CreateBranch", this.sourcePath, this.destinationPath);
        }
    }
}